<script setup>
  import { onMounted, ref } from 'vue'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { http } from '@/utils/http.js'

  const detail = ref('')
  const buynum = ref(0)
  const totalPrice = ref(0)
  const goodsId = ref(0)
  const addressid = ref(0)
  const freight = ref(0)
  const payType = ref(3)
  const agree = ref(true)
  const addressInfo = ref({
    province: '',
    city: '',
    area: '',
    address: '',
    name: '',
    mobile: '',
  })
  const goodsInfo = ref([])

  async function getDetail() {
    // console.log(detail.value[0])
    const res = await http.request({
      url: `/api/bag/${
        isShop.value == 1 ? 'createShopOrderPage' : 'createOrderPage'
      }`,
      method: 'POST',
      data: {
        goods_data: detail.value,
        // idArr: detail.value,
        address_id: addressid.value,
      },
    })
    console.log(res)
    addressInfo.value = res.data.address_info
    addressid.value = res.data.address_info.id
    balance.value = res.data.user_balance
    goodsInfo.value = res.data.data.map((e) => {
      return Object.assign({}, e, {
        buynum: detail.value.find((j) => j.goods_id == e.goods_id).num,
      })
    })
    // goodsInfo.value.forEach((item) => {
    //   console.log(
    //     detail.value.find((e) => e.goods_id == item.goods_id).num,
    //     'detail.value.find((e) => e.goods_id == item.goods_id).num'
    //   )
    //   buynum.value =
    // })
    console.log(goodsInfo.value, 'goodsInfogoodsInfogoodsInfo')
    if (res.data.freight.is_ps == 1) {
      freight.value = res.data.freight.freight
    } else {
      uni.utils.toast(res.data.freight.msg)
    }
  }
  // 地址弹窗
  const popup = ref()
  const addressList = ref()
  async function getaddressList() {
    const res = await http.request({
      url: '/api/address/myAddress',
      method: 'POST',
      data: {},
    })
    console.log(res)
    addressList.value = res.data
  }
  function addressPop() {
    getaddressList()
    popup.value.open('bottom')
  }

  function radioChange(evt) {
    console.log(evt)
    addressid.value = evt.detail.value
    addressList.value.forEach((item) => {
      if (addressid.value == item.id) {
        console.log(item)
        addressInfo.value = item
      }
      popup.value.close('bottom')
    })
    getDetail()
  }

  //选择支付方式
  function changePay(evt) {
    payType.value = evt.detail.value
  }

  // 创建订单
  const orderId = ref(0)
  async function createOrder() {
    if (!agree.value) {
      uni.utils.toast('请同意支付协议')
      return
    }
    const res = await http.request({
      url: `/api/bag/${isShop.value == 1 ? 'createShopOrder' : 'createOrder'}`,
      method: 'POST',
      data: {
        address_id: addressid.value,
        goods_data: detail.value,
        pay_type: payType.value,
      },
    })
    console.log(res)
    if (res.st == 1) {
      orderId.value = res.data
      if (payType.value == 3 || freight.value == 0) {
        uni.utils.toast('支付成功，即将跳转到订单详情页面')
        setTimeout(() => {
          uni.reLaunch({
            url: `/homePage/paysuccess/index?id=${
              orderId.value
            }&from=${'order'}`,
          })
        }, 2000)
      } else if (payType.value == 1 && freight.value != 0) {
        wxPay()
      }
    } else {
      uni.utils.toast(res.msg)
    }
  }

  //微信支付
  const timeStatu = ref(true)
  const paying = ref(1)
  async function wxPay() {
    const res = await http.request({
      url: '/api/adapay/adapay/adaPayOrder',
      method: 'POST',
      data: {
        id: orderId.value,
        type: 3,
      },
    })
    console.log(res)
    if (res.st == 1) {
      uni.navigateToMiniProgram({
        appId: res.data.expend.wx_app_id,
        path: res.data.expend.path,
        extraData: {},
        success(res) {
          // 打开成功
          paying.value = 2
        },
      })
    } else {
      uni.utils.toast('拉起支付失败，请联系客服~')
    }
  }

  // async function wxPay() {
  // 	const res = await http.request({
  // 		url: '/api/bag/wechatBagPay',
  // 		method: 'POST',
  // 		data: {
  // 			id: orderId.value,
  // 		},
  // 	})
  // 	console.log(res)
  // 	if (res.st == 1) {
  // 		uni.requestPayment({
  // 			provider: 'wxpay',
  // 			timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
  // 			nonceStr: res.data.nonceStr, // 随机字符串
  // 			package: res.data.package, // 固定值
  // 			signType: res.data.signType,
  // 			paySign: res.data.paySign, // 签名，这里用的 MD5 签名
  // 			success: function (res) {
  // 				console.log('success:' + JSON.stringify(res))
  // 				if (res.errMsg == 'requestPayment:ok') {
  // 					setTimeout(() => {
  // 						timeStatu.value = false
  // 					}, 5000)
  // 					wxPayAsk()
  // 				}
  // 			},
  // 			fail: function (err) {
  // 				uni.utils.toast('支付失败')
  // 				// console.log('fail:' + JSON.stringify(err))
  // 			},
  // 		})
  // 	} else {
  // 		uni.utils.toast(res.msg)
  // 	}
  // }

  //微信轮询
  async function wxPayAsk() {
    setTimeout(() => {
      timeStatu.value = false
    }, 5000)
    const res = await http.request({
      url: '/api/bag/getPayBagInfo',
      method: 'POST',
      data: {
        id: orderId.value,
      },
    })
    console.log(res)
    if (res.st == 1) {
      if (res.data.status == 2) {
        if (res.data.pay_st == 1) {
          uni.utils.toast('支付成功，即将跳转到订单详情页面')
          setTimeout(() => {
            uni.reLaunch({
              url: `/homePage/paysuccess/index?id=${
                orderId.value
              }&from=${'order'}`,
            })
          }, 2000)
        } else {
          uni.utils.toast(res.data.pay_msg)
        }
      } else {
        uni.utils.toast(res.msg)
      }
    } else {
      if (timeStatu.value) {
        wxPayAsk()
      } else {
        uni.utils.toast(res.msg)
      }
    }
    paying.value = 1
  }

  //跳转管理地址
  function manageAddress() {
    uni.navigateTo({
      url: `/minePage/address/index`,
    })
    popup.value.close('bottom')
  }

  function editAddress(item) {
    uni.navigateTo({
      url: `/minePage/editaddress/index?info=${encodeURIComponent(
        JSON.stringify(item)
      )}`,
    })
    popup.value.close('bottom')
  }

  // 用户信息卡尘(暂时)
  const balance = ref(0)
  //协议
  function goRule(id) {
    uni.navigateTo({
      url: `/homePage/agreement/index?id=${id}`,
    })
  }
  const isShop = ref(0)
  onLoad((option) => {
    isShop.value = option.isShop || 0
    detail.value = JSON.parse(decodeURIComponent(option.info))
    getaddressList()
    console.log(detail.value)
    detail.value.forEach((item) => {
      buynum.value += item.num
    })
  })
  onShow(() => {
    getDetail()
    if (paying.value == 2) {
      wxPayAsk()
    }
  })
</script>

<template>
  <view class="content">
    <view class="chooseaddress" @click="addressPop">
      <view class="addinfo">
        <view class="info">
          <text style="font-size: 24rpx">{{
            addressInfo.province + addressInfo.city + addressInfo.area
          }}</text>
          <text class="address-center">{{ addressInfo.address }}</text>
          <view style="font-size: 24rpx; color: #3d3d3d"
            >{{ addressInfo.name }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<text
              style="font-size: 22rpx; color: #898989"
              >{{ addressInfo.mobile }}</text
            ></view
          >
        </view>
        <view class="aim"> </view>
      </view>
    </view>
    <view class="spots">
      <view class="title">
        <view class="title-left"> 商品 </view>
        <view class="title-right"> 共{{ buynum }}件 </view>
      </view>

      <view class="bagGoods">
        <scroll-view
          class="scroll-view_H"
          scroll-x="true"
          v-if="goodsInfo.length"
        >
          <view
            class="scroll-item"
            v-for="item in goodsInfo"
            :key="'goods' + item.goods_id"
          >
            <view class="scroll-goods-img">
              <image
                style="width: 160rpx"
                :src="item.img"
                mode="widthFix"
              ></image>
            </view>
            <text
              style="display: inline-block; width: 80rpx; text-align: center"
              >￥{{ item.box_price }}</text
            >
            <text
              style="display: inline-block; width: 80rpx; text-align: center"
            >
              <text style="font-size: 16rpx">X</text>
              {{ item.buynum }}</text
            >
          </view>
        </scroll-view>
      </view>
    </view>
    <view class="express">
      <view style="font-size: 26rpx; color: #3d3d3d; font-weight: 700">
        配送
      </view>
      <view class="money">
        <text style="margin-right: 4rpx; color: #3d3d3d">快递</text>
        <text>{{ freight == 0 ? '包邮' : `￥${freight}` }}</text>
      </view>
    </view>

    <view class="pay">
      <view class="title"> 选择支付方式 </view>
      <view class="pay-list">
        <radio-group @change="changePay">
          <view class="group-item">
            <view>
              <radio
                style="transform: scale(0.8)"
                value="3"
                :checked="payType == 3"
              />
            </view>
            <view
              style="
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <view style="display: flex; align-items: center">
                <image
                  style="width: 54rpx; height: 42rpx; margin-right: 18rpx"
                  src="../../static/xinshi.png"
                  mode=""
                ></image>
                <text style="font-size: 24rpx">卡尘代扣</text>
              </view>
              <text style="font-size: 24rpx; color: #898989"
                >￥{{ balance }}</text
              >
            </view>
          </view>
          <view class="group-item">
            <view>
              <radio
                style="transform: scale(0.8)"
                value="1"
                :checked="payType == 1"
              />
            </view>
            <view
              style="
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <view style="display: flex; align-items: center">
                <image
                  style="width: 52rpx; height: 52rpx; margin-right: 18rpx"
                  src="../../static/weixinpay.png"
                  mode=""
                ></image>
                <text style="font-size: 24rpx">微信支付</text>
              </view>
            </view>
          </view>
          <!-- <view class="group-item">
						<view>
							<radio
								style="transform: scale(0.8)"
								value="2"
								:checked="payType == 2"
							/>
						</view>
						<view
							style="
								width: 100%;
								display: flex;
								align-items: center;
								justify-content: space-between;
							"
						>
							<view style="display: flex; align-items: center">
								<image
									style="
										width: 52rpx;
										height: 52rpx;
										margin-right: 18rpx;
									"
									src="../../static/zhifubbao.png"
									mode=""
								></image>
								<text style="font-size: 24rpx">支付宝</text>
							</view>
						</view>
					</view> -->
        </radio-group>
      </view>
    </view>
    <view class="bottom">
      <view class="bottom-left">
        <label>
          <checkbox
            @click="agree = !agree"
            value="cb"
            :checked="agree"
            color="#FFF"
            style="transform: scale(0.8)"
          />
          <text style="font-size: 26rpx; color: #b1b0b8">同意</text>
          <text class="agree" @tap.stop="goRule(5)">《平台用户服务协议》</text>
        </label>
        <view class="total">
          <text style="font-size: 25rpx">￥</text>
          <text style="font-size: 36rpx">{{ freight }}</text>
        </view>
      </view>
      <button type="primary" @click="createOrder">提交订单</button>
    </view>
    <!-- 地址信息弹窗 -->
    <uni-popup ref="popup" type="bottom">
      <view class="popup-content">
        <text class="title">收货地址</text>
        <scroll-view scroll-y="true" class="scroll-Y" style="height: 82%">
          <radio-group
            @change="radioChange"
            style="height: 80%; overflow: auto; padding-bottom: 20rpx"
          >
            <view
              class="radio"
              v-for="item in addressList"
              :key="item.address + item.id"
            >
              <view class="left">
                <radio
                  style="transform: scale(0.8)"
                  :value="item.id"
                  :checked="item.id == addressid"
                />
                <view class="address">
                  <text style="font-size: 24rpx">{{
                    item.province + item.city + item.area
                  }}</text>
                  <text class="address-center">{{ item.address }}</text>
                  <view style="font-size: 24rpx; color: #3d3d3d"
                    >{{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<text
                      style="font-size: 22rpx; color: #898989"
                      >{{ item.mobile }}</text
                    ></view
                  >
                </view>
              </view>
              <image
                style="width: 34rpx; height: 34rpx"
                src="../../static/edit.png"
                mode=""
                @click="editAddress(item)"
              ></image>
            </view>
          </radio-group>
        </scroll-view>
        <button type="primary" @click="manageAddress">地址管理</button>
      </view>
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
  .content {
    background: #f4f4f4;
    height: 100vh;
    padding-top: 24rpx;
    .chooseaddress {
      display: flex;
      align-items: center;
      height: 160rpx;
      // margin: 24rpx 0;
      padding: 0 42rpx;
      background-color: #fff;
      box-sizing: border-box;
      .addinfo {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .info {
          display: flex;
          flex-direction: column;
          margin-right: 60rpx;
        }
        .address-center {
          width: 100%;
          font-size: 28rpx;
          color: #3d3d3d;
          line-height: 62rpx;

          display: -webkit-box;
          -webkit-line-clamp: 1; /* 限制为两行 */
          -webkit-box-orient: vertical;
          overflow: hidden; /* 隐藏超出部分 */
          text-overflow: ellipsis; /* 超出部分用省略号表示 */
          white-space: normal; /* 允许换行 */
          /* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
          text-align: left;
        }
        .aim {
          width: 15rpx;
          height: 15rpx;
          border-top: 1px solid #b1b0b8;
          border-right: 1px solid #b1b0b8;
          transform: rotate(45deg);
        }
      }
    }
    .spots {
      padding: 20rpx;
      padding-bottom: 60rpx;
      margin-top: 20rpx;
      background-color: #fff;
      box-sizing: border-box;
      .title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 800;
        font-size: 26rpx;
        color: #3d3d3d;
        .title-right {
          font-size: 24rpx;
          font-weight: normal;
        }
      }
      .goods {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 26rpx;
        .details {
          width: 70%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .goods_name {
            height: 65rpx;
            width: 100%;
            // padding: 22rpx;
            font-size: 24rpx;
            text-align: left;
            box-sizing: border-box;

            display: -webkit-box;
            -webkit-line-clamp: 2; /* 限制为两行 */
            -webkit-box-orient: vertical;
            overflow: hidden; /* 隐藏超出部分 */
            text-overflow: ellipsis; /* 超出部分用省略号表示 */
            white-space: normal; /* 允许换行 */
            /* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
          }
        }
      }
      .bagGoods {
        margin-top: 26rpx;
        .scroll-view_H {
          white-space: nowrap;
          width: 100%;
          .scroll-item {
            display: inline-block;
            margin-right: 20rpx;
            &:last-child {
              margin-right: 0;
            }
            .scroll-goods-img {
              width: 160rpx;
              // height: 160rpx;
              border-radius: 8rpx;
              overflow: hidden;
            }
            text {
              font-size: 22rpx;
            }
          }
        }
      }
    }
    .express {
      height: 96rpx;
      margin: 20rpx 0;
      padding: 0 22rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      box-sizing: border-box;
      .money {
        font-size: 25rpx;
        color: $all-color;
      }
    }
    .pay {
      height: 370rpx;
      padding: 26rpx;
      background-color: #fff;
      box-sizing: border-box;
      .title {
        font-weight: 800;
        font-size: 26rpx;
        color: #3d3d3d;
      }
      .group-item {
        display: flex;
        align-items: center;
        padding: 22rpx 0;
        // radio选中时背景颜色设置
        ::v-deep radio .wx-radio-input.wx-radio-input-checked {
          background-color: $all-color !important;
          border: 1px solid $all-color !important;
        }
      }
    }
    .bottom {
      position: fixed;
      bottom: 0;
      display: flex;
      align-items: center;
      height: 222rpx;
      width: 100%;
      padding: 0 0 0 20rpx;
      background-color: #fff;
      box-sizing: border-box;
      .bottom-left {
        width: 70%;
        display: flex;
        flex-direction: column;
        .agree {
          font-size: 26rpx;
          color: $all-color;
        }
        ::v-deep checkbox .wx-checkbox-input.wx-checkbox-input-checked {
          color: #fff;
          background: $all-color;
        }

        ::v-deep .wx-checkbox-input.wx-checkbox-input-checked {
          border: 1px solid $all-color;
        }
        .total {
          margin-top: 15rpx;
          padding-left: 6rpx;
          color: $all-color;
        }
      }
      button {
        height: 66rpx;
        padding: 0 34rpx;
        border-radius: 33rpx;
        background-color: $all-color;
        font-size: 26rpx;
        line-height: 66rpx;
      }
    }
    // 地址弹出框
    .popup-content {
      align-items: center;
      justify-content: center;
      padding: 30rpx;
      height: 750rpx;
      background-color: #fff;
      border-radius: 22rpx 22rpx 0 0;
      box-sizing: border-box;
      text-align: center;
      .title {
        margin-bottom: 82rpx;
        font-size: 28rpx;
        color: #3d3d3d;
      }
      .radio {
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        // margin-top: 26rpx;
        padding: 22rpx 0;
        border-bottom: 1px solid #f5f5f5;
        &:last-child {
          border: none;
        }
        // radio选中时背景颜色设置
        ::v-deep radio .wx-radio-input.wx-radio-input-checked {
          background-color: $all-color !important;
          border: 1px solid $all-color !important;
        }
        .left {
          width: 80%;
          display: flex;
          align-items: center;
          .address {
            display: flex;
            flex-direction: column;
            align-items: start;
            margin-left: 36rpx;
            .address-center {
              width: 100%;
              font-size: 28rpx;
              color: #3d3d3d;
              line-height: 48rpx;
              text-align: left;

              display: -webkit-box;
              -webkit-line-clamp: 1; /* 限制为两行 */
              -webkit-box-orient: vertical;
              overflow: hidden; /* 隐藏超出部分 */
              text-overflow: ellipsis; /* 超出部分用省略号表示 */
              white-space: normal; /* 允许换行 */
              /* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
            }
          }
        }
      }
      button {
        height: 82rpx;
        border-radius: 41rpx;
        background: $all-color;
        line-height: 82rpx;
        font-size: 28rpx;
      }
    }
  }
</style>
